//
//  OTC_SellOutVC.m
//  Exchange
//
//  Created by 张庆勇 on 2019/2/28.
//  Copyright © 2019年 张庆勇. All rights reserved.
//

#import "OTC_SellOutVC.h"
#import "OTCTableViewCell.h"
#import "tableViewFooterView.h"
#import "DropDownAlertVC.h"
#import "OTCDropView.h"
#import "OTCModel.h"
#import "LoginViewController.h"
#import "OTC_WaitingpaymentVC.h"
#import "CheckVersionAlearView.h"
#import "PaymentSetVC.h"
#import "CountryListViewController.h"
#import "PaypalCustomAlert.h"
#import "PaypalModel.h"
#import "IdentityAuthenticationViewController.h"
#import "CapitalPasswordViewController.h"
@interface OTC_SellOutVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)tableViewFooterView *footerView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSMutableArray *PayPalIds;
@property (nonatomic,strong)NSMutableArray *paypalArray;
@property (assign,nonatomic)NSUInteger         pages;
@property (nonatomic,strong)NoNetworkView * workView;
@property (nonatomic,strong)NSMutableString * mutaStr;
@property (nonatomic,strong)NSString * pay_method;
@property (nonatomic,assign)NSInteger  index;
@property (nonatomic,assign)NSInteger  bankindex;
@end
@implementation OTC_SellOutVC

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([EXUserManager isLogin])
    {
        [self getPay];
    }
    _index =10086;
    [self.view addSubview:self.tableView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getPay) name:bindbnakNotificationse object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(LoginSusess) name:LoginSusessNotificationse object:nil];
    // 上拉加载
    WeakSelf
    WLRefreshGifHeader *header = [WLRefreshGifHeader headerWithRefreshingBlock:^{
        weakSelf.pages = 0;
        [weakSelf getData];
        
    }];
    [header beginRefreshing];
    self.tableView.mj_header = header;
    EXRefrechFootview *fooder = [EXRefrechFootview footerWithRefreshingBlock:^{
        weakSelf.pages++;
        [weakSelf getData];
    }];
    self.tableView.mj_footer = fooder;
}
- (void)LoginSusess
{
    [self getPay];
}
/*获取支付方式*/
- (void)getPay
{
    WeakSelf
    [HomeViewModel  getMobilePayDataListWithDic:@{} url:mobilePay callBack:^(BOOL isSuccess, id callBack) {
        if (isSuccess) {
            NSArray * list = callBack[@"result"][@"banks"];
            NSArray * logs = callBack[@"result"][@"logs"];
            weakSelf.mutaStr = [[NSMutableString alloc] init];
            if (list.count>0)
            {
                if (logs.count==0) {
                    [weakSelf.mutaStr appendFormat:@"0"];
                }else
                {
                    [weakSelf.mutaStr appendFormat:@"0,"];
                }
                [weakSelf.PayPalIds addObject:list[0][@"ID"]];
                
            }
            for (NSDictionary * dic in logs)
            {
                if ([dic[@"status"] integerValue] ==1) //支付宝
                {
                    if (logs.count ==1)
                    {
                        [weakSelf.mutaStr appendFormat:@"1"];
                    }else
                    {
                        [weakSelf.mutaStr appendFormat:@"1,"];
                    }
                    
                }else
                {
                    [weakSelf.mutaStr appendFormat:@"2"];
                }
                [weakSelf.PayPalIds addObject:dic[@"ID"]];
            }
            
        }
    }];
}
- (void)refrech
{
    _pages = 0;
    [self getData];
}
#pragma mark----数据
- (void)getData
{
    WeakSelf
    [self GETWithHost:@"" path:getMerchant param:@{@"type":@"2",@"payMethod":@"",@"offset":@(self.pages*10),@"limit":@(10)} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self.tableView.mj_header endRefreshing];
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            NSArray *list = responseObject[@"result"][@"logs"];
            if (weakSelf.pages > 0)
            {
                [weakSelf.dataArray addObjectsFromArray:[OTCModel mj_objectArrayWithKeyValuesArray:list]];
                if (list.count<10)
                {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }
                
            }else
            {
                weakSelf.dataArray = [OTCModel mj_objectArrayWithKeyValuesArray:list];
                if (list.count<10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }
                
            }
            [self placeholderViewWithFrame:weakSelf.tableView.frame NoNetwork:NO];
            [weakSelf.tableView reloadData];
            
        }else
        {
            [EXUnit showMessage:responseObject[@"message"]];
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    if (_dataArray.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:frame NoNetwork:NoNetwork];
        if (NoNetwork) {
            WeakSelf
            _workView.buttonclickeBlock = ^(UIButton *button) { //重新加载
                [weakSelf getData];
            };
        }
        _tableView.tableFooterView = [[UIView alloc] init];
        [self.tableView addSubview:_workView];
    }else
    {
        _tableView.tableFooterView = self.footerView;
        [_workView dissmiss];
    }
}
#pragma mark----n懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight -49 -64 -IPhoneTop -RealValue_W(88))];
        _tableView.separatorColor = CELLCOLOR;
        _tableView.backgroundColor = TABLEVIEWLCOLOR;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[OTCTableViewCell class] forCellReuseIdentifier:@"OTCTableViewCell"];
        _tableView.tableFooterView = self.footerView;
        
    }
    return _tableView;
}
- (tableViewFooterView *)footerView
{
    if (!_footerView) {
        _footerView = [[tableViewFooterView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 0)];
        _footerView.height = [_footerView getViewHeight];
    }
    return _footerView;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (NSMutableArray *)PayPalIds
{
    if (!_PayPalIds) {
        _PayPalIds = [[NSMutableArray alloc]init];
    }
    return _PayPalIds;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_index ==indexPath.row) {
        return RealValue_H(416);
    }
    return RealValue_H(210);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return RealValue_H(20);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * view  = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, RealValue_H(20))];
    view.backgroundColor = [ZBLocalized sharedInstance].BgViewLightColor;
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OTCTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"OTCTableViewCell"];
    if (indexPath.row ==_index) {
        cell.tradeBgView.hidden = NO;
        cell.bottomView.mj_y = cell.tradeBgView.bottom;
    }else
    {
        cell.tradeBgView.hidden = YES;
        cell.bottomView.mj_y = cell.bgView.bottom;
    }
    cell.isSell = YES;
    cell.model = _dataArray[indexPath.row];
    [cell.buyButton add_BtnClickHandler:^(NSInteger tag) {
        
        [self sellOTCSymbolWithIndexPath:indexPath];
    }];
    WeakSelf
    [cell.cancelButton add_BtnClickHandler:^(NSInteger tag) {
        
        weakSelf.index =10086;
        [weakSelf.tableView reloadData];
    }];
    WeakObject(cell)
    [cell.okbutton add_BtnClickHandler:^(NSInteger tag) {
        
        [self tradeWithTableViewCell:weakcell indexPath:indexPath];
    }];
    return cell;
}
/*购买OTC*/
- (void)sellOTCSymbolWithIndexPath:(NSIndexPath *)indexPath
{
    
    _index = indexPath.row;
    [self.tableView reloadData];
    
}
- (void)SetThePassword
{
    LoginViewController * loginView = [[LoginViewController alloc] init];
    [[EXUnit currentViewController] presentViewController:loginView animated:YES completion:nil];
}
#pragma make  选择支付方式
- (void)choosePaypalWithTableViewCell:(OTCTableViewCell *)cell indexPath:(NSIndexPath *)indexPath
{
    
    WeakSelf
     OTCModel * model = _dataArray[indexPath.row];
    
    
    
    if ([EXUserManager personalData].withdraw_password_set) {
        CountryListViewController * custom = [[CountryListViewController alloc] initWithCustomContentViewClass:@"PaypalCustomAlert" delegate:nil];
        custom.direction = FromBottom;
        [custom showWith:self.paypalArray wihtISSell:YES];
        PaypalCustomAlert *aleatView = (PaypalCustomAlert *)custom.contentView;
        aleatView.index = weakSelf.bankindex;
        aleatView.cancelBlock = ^{
            [custom dismiss];
        };
        WeakObject(aleatView)
        aleatView.selectIndexPathRow = ^(NSInteger index,NSString * capital) {
            [custom dismiss];
            weakSelf.bankindex = index;
            PaypalModel * payModel = weakSelf.paypalArray[index];
            weakSelf.pay_method = [NSString stringWithFormat:@"%@",payModel.id];
            if ([NSString isEmptyString:weakaleatView.capitalField.text])
            {
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:Localized(@"Security_Password_funds_message") view:kWindow];
                return ;
            }
            [weakSelf POSTWithHost:@"" path:otc_trade param:@{@"amount":cell.numberField.text,@"type":@"2",@"merchant_account_id":model.merchant_account_id,@"withdraw_password":weakaleatView.capitalField.text,@"pay_method":weakSelf.pay_method,@"pay_method_id":[NSString stringWithFormat:@"%@",weakSelf.PayPalIds[index]]} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                if ([responseObject[@"code"] integerValue]==0)//成功
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:OTCPaypalNotificationse object:nil];
                    OTC_WaitingpaymentVC *  waitingpayment = [[OTC_WaitingpaymentVC alloc] init];
                    waitingpayment.type = [NSString stringWithFormat:@"%@",responseObject[@"result"][@"order"][@"type"]];
                    waitingpayment.order_no = responseObject[@"result"][@"order"][@"order_no"];
                    [self.navigationController pushViewController:waitingpayment animated:YES];
                    [custom dismiss];
                    [self refrech];
                    
                }else
                {
                    NSMutableString * str = [[NSMutableString alloc] init];
                    if ([model.pay_method containsString:@"0"]) {
                        
                        [str appendFormat:@"%@ ",Localized(@"C2C_Bank_card")];
                        
                    }else if ([model.pay_method containsString:@"1"])
                    {
                        [str appendFormat:@"%@ ",Localized(@"OTC_alipay")];
                    }else if ([model.pay_method containsString:@"2"])
                    {
                        [str appendFormat:@"%@ ",Localized(@"OTC_weChat")];
                    }
                    [EXUnit showMessage:responseObject[@"message"]];
                    
                }
                [weakaleatView.OKbutton stopAnimation];
                
            } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [weakaleatView.OKbutton stopAnimation];
            }];
        };
    }else
    {
        CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:Localized(@"Asset_capital_message")
                                                                                 titleStr:Localized(@"C2C_Reminder")
                                                                                  openUrl:@""
                                                                                  confirm:Localized(@"transaction_OK")
                                                                                   cancel:Localized(@"transaction_cancel")
                                                                                    state:2
                                                                            RechargeBlock:^
                                            {
                                                
                                                CapitalPasswordViewController *  Capitalpass  = [[CapitalPasswordViewController alloc] init];
                                                Capitalpass.isEdit = NO;
                                                Capitalpass.title = [EXUserManager personalData].withdraw_password_set?Localized(@"Security_fund_password"):Localized(@"Security_Set_funds_password");
                                                [self.navigationController pushViewController:Capitalpass animated:YES];
                                                
                                            }];
        aleartVC.animationStyle = LXASAnimationLeftShake;
        [aleartVC showLXAlertView];
        
    }
   
}
#pragma make  安全操作
- (void)tradeWithTableViewCell:(OTCTableViewCell *)cell indexPath:(NSIndexPath *)indexPath
{
    [cell.numberField resignFirstResponder];
    [cell.priceField resignFirstResponder];
    if (![EXUserManager isLogin])
    {
        [self SetThePassword];
        return;
    }
    if ([[EXUnit getSite] isEqualToString:@"ZT"]) {
        if (![[EXUserManager personalData].country_code isEqualToString:@"+886"])
        {
            [EXUnit showMessage:Localized(@"OTC_Taiwan_user_message")];
            return;
        }
    }
    WeakSelf
    if ([AppDelegate shareAppdelegate].isBecomeActive) {
        if ([EXUnit isOpenTouchid] && ![EXUnit isOpenGesture]) {
            [YWFingerprintVerification fingerprintVerificationCallBack:^(NSError *error) {
                if(!error){
                    //验证成功，主线程处理UI
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        // 处理耗时操作的代码块...
                        
                        //通知主线程刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakSelf sellWithTableViewCell:cell indexPath:indexPath];
                        });
                        
                    });
                }else{
                    //验证成功，主线程处理UI
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        // 处理耗时操作的代码块...
                        
                        //通知主线程刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [EXUserManager removeUserInfo];
                            [weakSelf SetThePassword];
                        });
                        
                    });
                    
                }
            }];
        }else if (![EXUnit isOpenTouchid] && [EXUnit isOpenGesture])
        {
            //验证手势密码
            [YWUnlockView showUnlockViewWithType:YWUnlockViewUnlock callBack:^(BOOL result) {
                if (result) {
                    [weakSelf sellWithTableViewCell:cell indexPath:indexPath];
                }else
                {
                    [EXUserManager removeUserInfo];
                    [weakSelf SetThePassword];
                }
                
                
            }];
            
        }else if (![EXUnit isOpenTouchid] && ![EXUnit isOpenGesture])
        {
            [weakSelf sellWithTableViewCell:cell indexPath:indexPath];
        }
    }else
    {
        [weakSelf sellWithTableViewCell:cell indexPath:indexPath];
    }
}
#pragma make  银行卡处理逻辑
- (void)sellWithTableViewCell:(OTCTableViewCell *)cell indexPath:(NSIndexPath *)indexPath
{
    WeakSelf
    [AppDelegate shareAppdelegate].isBecomeActive = NO;
    if ([EXUserManager RealName].integerValue ==0) { //未认证
        [self popRealName:YES title:Localized(@"transaction_authenticated_title") message:Localized(@"transaction_authenticated_message")];
        
        
    }else if ([EXUserManager RealName].integerValue ==1 ||[EXUserManager RealName].integerValue ==4)//审核中
    {
        [EXUnit showMessage:Localized(@"C2C_under_review")];
        
        
        
    }else if ([EXUserManager RealName].integerValue ==3)//认证失败
    {
        
        [self popRealName:YES title:Localized(@"transaction_authenticated_title") message:Localized(@"transaction_authenticated_failed")];
        
        
        
    }else if ([EXUserManager RealName].integerValue ==2)//认证成功
    {
        OTCModel * model = _dataArray[indexPath.row];
        if ([NSString isEmptyString:weakSelf.mutaStr])
        {
            [self popRealName:NO title:Localized(@"C2C_bank_card") message:Localized(@"C2C_bank_card_message")];
            return;
        }
        if ([NSString isEmptyString:cell.numberField.text] || cell.numberField.text.floatValue==0)
        {
            [weakSelf axcBasePopUpWarningAlertViewWithMessage:Localized(@"OTC_Rquantity_order_mgs") view:kWindow];
            return ;
        }
        if (cell.numberField.text.floatValue< model.limit_money_lower.floatValue || cell.numberField.text.floatValue > model.limit_money_higher.floatValue)
        {
             [weakSelf axcBasePopUpWarningAlertViewWithMessage:[NSString stringWithFormat:Localized(@"OTC_money_lower_message"),model.limit_money_lower,model.limit_money_higher] view:kWindow];
            return ;
        }
        
        
        NSMutableArray * titles = [NSMutableArray new];
        NSMutableArray * imgs = [NSMutableArray new];
        NSMutableArray * ids = [NSMutableArray new];
        if ([model.pay_method containsString:@"0"]&& [weakSelf.mutaStr containsString:@"0"]) {
            
            [titles addObject:Localized(@"C2C_Bank_card")];
            [imgs addObject:@"otc_icon_card"];
            [ids addObject:@"0"];
            
        }
        if ([model.pay_method containsString:@"1"] && [weakSelf.mutaStr containsString:@"1"])
        {
            [titles addObject:Localized(@"OTC_alipay")];
            [imgs addObject:@"otc_icon_zhi"];
            [ids addObject:@"1"];
        }
        if ([model.pay_method containsString:@"2"] && [weakSelf.mutaStr containsString:@"2"])
        {
            [titles addObject:Localized(@"OTC_weChat")];
            [imgs addObject:@"otc_icon_vx"];
            [ids addObject:@"2"];
        }
        _paypalArray = [[NSMutableArray alloc] init];
        for (int i=0; i<titles.count; i++)
        {
            PaypalModel * model = [[PaypalModel alloc] init];
            model.icon = imgs[i];
            model.title = titles[i];
            model.id = ids[i];
            [self.paypalArray addObject:model];
        }
        if (self.paypalArray.count==0) {
            [EXUnit showMessage:Localized(@"OTC_sell_paypal_message")];
            return;
        }else
        {
            [self choosePaypalWithTableViewCell:cell indexPath:indexPath];
        }
    }
   
}
- (void)popRealName:(BOOL)isRealName title:(NSString *)title message:(NSString *)message
{
    if (isRealName) {
        CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:message
                                                                                 titleStr:title
                                                                                  openUrl:@""
                                                                                  confirm:Localized(@"transaction_OK")
                                                                                   cancel:Localized(@"transaction_cancel")
                                                                                    state:2
                                                                            RechargeBlock:^
                                            {
                                                
                                                IdentityAuthenticationViewController * idACationVC = [[IdentityAuthenticationViewController alloc] init];
                                                idACationVC.title = Localized(@"my_identity_authentication");
                                                [[EXUnit currentViewController].navigationController pushViewController:idACationVC animated:YES];
                                                
                                                
                                            }];
        aleartVC.animationStyle = LXASAnimationTopShake;
        [aleartVC showLXAlertView];
    }else
    {
        CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:message
                                                                                 titleStr:title
                                                                                  openUrl:@""
                                                                                  confirm:Localized(@"transaction_OK")
                                                                                   cancel:Localized(@"transaction_cancel")
                                                                                    state:2
                                                                            RechargeBlock:^{
                                                                                
                                                                                PaymentSetVC * bindbank = [[PaymentSetVC alloc] init];
                                                                                bindbank.title = Localized(@"OTC_Payment_Settings");
                                                                                [self.navigationController pushViewController:bindbank animated:YES];
                                                                                
                                                                            }];
        aleartVC.animationStyle = LXASAnimationTopShake;
        [aleartVC showLXAlertView];
    }
}

@end
